package com.hightemperator.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class CommonUtil {
    private static Log log = LogFactory.getLog(CommonUtil.class);

    /**
     * 生成随机验证码
     *
     * @return
     */
    public static String getRandom4() {
        Random random = new Random();
        String result = "";
        for (int i = 1; i <= 4; i++) {
            result += random.nextInt(10);
        }
        return result;
    }


    public static int getOrderNo() {
        String orderNo = "";
        String trandNo = String.valueOf((Math.random() * 9 + 1) * 1000000);
        String sdf = new SimpleDateFormat("yyyyMMddHHMMSS").format(new Date());
        orderNo = trandNo.toString().substring(0, 4);
        orderNo = orderNo + sdf.substring(10, sdf.length());
        return Integer.parseInt(orderNo);
    }


    /**
     * 生成随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomStr(int length) {
        if (length == 32) {
            return UUID.randomUUID().toString().replaceAll("-", "");
        } else {
            return UUID.randomUUID().toString().replaceAll("-", "").substring(0, length + 1);
        }
    }

    /**
     * 获取普通时间
     *
     * @return
     */
    public static String getSimpleDate() {
        Date d = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(d);
    }

    /***
     * 构建api签名
     *
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String createSign(JSONObject params, boolean encode) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            if (encode) {
                temp.append(URLEncoder.encode(valueString, "UTF-8"));
            } else {
                temp.append(valueString);
            }
        }
        log.info("签名参数:" + params);
        log.info("签名字符串: " + temp.toString());
        return MD5Util.MD5Encode(temp.toString(), null).toUpperCase();
    }


}
